//
// <copyright file="LogHttpErrors.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
using System;
using System.Web;
using Microsoft.ServiceHosting.ServiceRuntime;

namespace UlyssesAgenda.FabricCommon
{
    public class LogErrorsHttpModule : IHttpModule
    {

        private HttpApplication context;

        public void Dispose()
        {
            context.Dispose();
        }

        public void Init(HttpApplication context)
        {
            this.context = context;
            ApplicationEnvironment.LogInformation("Logging module initalized.");
          
            // Requests using managed code does have performance implication.
            // Therefore we use a configuration setting for this, so that the site manager
            // could dynamically turn on or turn off the logging without service redeployment.
            bool logAllRequests = false;
            bool logFailedRequests = true;
            string valueLogAllRequests= ApplicationEnvironment.Settings["LogAllRequests"];
            string valueLogFailedRequests = ApplicationEnvironment.Settings["LogFailedRequests"];
            // Change this setting causes the site to restart, so we just need to register 
            // the right events on start.
            if (!bool.TryParse(valueLogAllRequests, out logAllRequests))
            {
                ApplicationEnvironment.LogError("Bad value for LogAllRequest should be 'true' or 'false'. Found:{0}",
                    valueLogAllRequests);
            }
            if (!bool.TryParse(valueLogFailedRequests, out logFailedRequests))
            {
                ApplicationEnvironment.LogError("Bad value for LogFailedRequest should be 'true' or 'false'. Found:{0}",
                    valueLogFailedRequests);
            }
           
            if (logAllRequests)
            {
                ApplicationEnvironment.LogInformation("Logging for all request enabled.");
                context.LogRequest += new EventHandler(OnLogRequest);
            }
            else
            {
                ApplicationEnvironment.LogInformation("Logging for all request disabled.");
            }

            if (logFailedRequests)
            {
                ApplicationEnvironment.LogInformation("Logging for failed request enabled.");
                context.Error += new EventHandler(OnError);
            }
            else
            {
                ApplicationEnvironment.LogInformation("Logging for failed request disabled.");
            }
        }

        private void OnLogRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;
            context.Response.DisableKernelCache();
            ApplicationEnvironment.LogInformation("\nRequest:\n{0}Response-Code: {1}",
                Format.HttpRequestAsText(context.Request),
                context.Response.StatusCode + "." + context.Response.SubStatusCode);

        }

        private void OnError(object sender, EventArgs e)
        {
            Exception ex = context.Server.GetLastError();
            if (ex.InnerException != null)
            {
                ex = ex.InnerException;
            }

            if (context.Request != null)
            {
                ApplicationEnvironment.LogError("\nUnhandled-Exception:\n{0}Request-Details:\n{1}",
                    Format.ExceptionAsText(ex),
                    Format.HttpRequestAsText(context.Request));
            }
            else
            {
                ApplicationEnvironment.LogError("\nUnhandled-Exception:\n{0}",
                    Format.ExceptionAsText(ex));
            }
        }
    }
}
